package com.sita.tboard.ui.activity;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.colintmiller.simplenosql.NoSQL;
import com.colintmiller.simplenosql.NoSQLEntity;
import com.colintmiller.simplenosql.RetrievalCallback;
import com.nostra13.universalimageloader.utils.L;
import com.sita.bike.R;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Audio;
import com.sita.bike.rest.model.Picture;
import com.sita.bike.rest.model.RtResource;
import com.sita.bike.rest.model.RtResourceNote;
import com.sita.bike.rest.model.request.RtLeaveNoteListRequest;
import com.sita.bike.rest.model.request.RtLeaveNoteNewRequest;
import com.sita.bike.rest.model.response.RtResourceNoteListResponse;
import com.sita.bike.rest.model.response.RtResourceNoteNewResponse;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.PersistUtils;
import com.sita.tboard.ui.adapter.RtResNoteListAdapter;
import com.sita.tboard.ui.adapter.TrendsGridAdapter;
import com.sita.tboard.ui.tools.AudioPlayer;
import com.sita.tboard.ui.view.CircleImageView;
import com.sita.tboard.ui.view.NoScrollGridView;
import com.sita.tboard.util.DateUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiaodong on 16/1/26.
 */
public class RtTrendDetailActivity extends AppCompatActivity {

    @Bind(R.id.user_avatar)
    CircleImageView viewAvatar;
    @Bind(R.id.user_nickname)
    TextView viewNickname;
    @Bind(R.id.resource_voice)
    ImageView viewVoice;
    @Bind(R.id.resource_time)
    TextView viewTime;
    @Bind(R.id.resource_content)
    TextView viewContent;
    @Bind(R.id.resource_gallery)
    GridView gallery;

    @Bind(R.id.resource_note_message)
    EditText viewNoteMessage;
    @Bind(R.id.resource_note_list)
    ListView viewListView;

    @Bind(R.id.rt_resource_toolbar)
    Toolbar toolbar;

    private int pageSize = 10;

    private AudioPlayer player;
    private AnimationDrawable mAnimationDrawable;

    public static final String BIND_RESOURCE_ID = "RESOURCE_ID";
    public static final String BIND_RESOURCE = "RESOURCE";

    private Parcelable listViewState;
    private RtResNoteListAdapter adapter;
    private String resourceId;

    private AtomicBoolean likable = new AtomicBoolean(true);

    private RtResource resource;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rt_trend_detail);
        ButterKnife.bind(this);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationIcon(R.mipmap.ic_back);

        player = getPlayer();

        resourceId = (String) getIntent().getStringExtra(BIND_RESOURCE_ID);
        resource = (RtResource) getIntent().getSerializableExtra(BIND_RESOURCE);
        String from = (String) getIntent().getStringExtra("from");
        if (resourceId == null && resource == null) {
            RtTrendDetailActivity.this.finish();
        } else {
            if (resource == null) {
                performLoadResource(resourceId, from);
            } else {
                populateRtResource();
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (resourceId == null && resource == null) {
            RtTrendDetailActivity.this.finish();
            return;
        }

        if (adapter == null) {
            adapter = new RtResNoteListAdapter(this);
            viewListView.setAdapter(adapter);
        }

        if (listViewState != null) {
            L.d("trying to restore listView state..");
            viewListView.onRestoreInstanceState(listViewState);
        }
    }

    private AudioPlayer getPlayer() {
        if (player != null) {
            if (player.isPlaying())
                player.stop();
        } else {
            player = new AudioPlayer();
        }
        //if everything ok play file
        //in case of any error return from method before (catch)
        return player;
    }

    @Override
    protected void onPause() {
        super.onPause();

        listViewState = viewListView.onSaveInstanceState();
        if (player != null && player.isPlaying()) {
            player.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.stop();
        }
    }

    @OnClick(R.id.resource_note_btn_send)
    void sendNoteMessage() {
        if (TextUtils.isEmpty(viewNoteMessage.getText().toString())) {
            return;
        }
        String message = viewNoteMessage.getText().toString();
        RtLeaveNoteNewRequest request = new RtLeaveNoteNewRequest();
        request.accountId = AccountUtils.getAccountID();
        request.resId = TextUtils.isEmpty(resourceId) ? resource.id : resourceId;
        request.message = message;
        RestClient.getRestNormalService().rtResourceNewNote(request, new Callback<RtResourceNoteNewResponse>() {
            @Override
            public void success(RtResourceNoteNewResponse reply, Response response) {
                viewNoteMessage.setText(null);
                if (response.getStatus() == 200 && reply.errorCode.equals("0")) {
                    List<RtResourceNote> notes = reply.data;
                    for (RtResourceNote note : notes) {
                        adapter.addLastItem(note);
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
                L.e(error);
                Toast.makeText(GlobalContext.getGlobalContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void performLoadNoteList(String resourceId) {
        RtLeaveNoteListRequest request = new RtLeaveNoteListRequest();
        request.resId = resourceId;
        RestClient.getRestNormalService().rtResourceListNote(request, new Callback<RtResourceNoteListResponse>() {
            @Override
            public void success(RtResourceNoteListResponse reply, Response response) {
                if (response.getStatus() == 200 && reply.errorCode.equals("0")) {
                    List<RtResourceNote> notes = reply.data.notes;
                    for (RtResourceNote note : notes) {
                        adapter.addLastItem(note);
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
                L.e(error);
            }
        });
    }

    private void performLoadResource(String resourceId, String from) {
        NoSQL.with(GlobalContext.getGlobalContext()).using(RtResource.class)
                .bucketId(Constants.RT_RESOURCE_BUCKET)
                .entityId(resourceId)
                .retrieve(new RetrievalCallback<RtResource>() {
                    @Override
                    public void retrievedResults(List<NoSQLEntity<RtResource>> noSQLEntities) {
                        if (!noSQLEntities.isEmpty()) {
                            resource = noSQLEntities.get(0).getData();
                            populateRtResource();
                        }
                    }
                });
    }

    private void populateRtResource() {
        viewNickname.setText(PersistUtils.getTrendMember(resource.accountId).getNickname());
        viewContent.setText(resource.title);

        String time = DateUtils.translateDateTime(resource.createDate);
        viewTime.setText(time);

        likable.set(resource.votable);

        Picasso.with(GlobalContext.getGlobalContext()).load(PersistUtils.getTrendMember(resource.accountId).getAvatarUrl()).fit()
                .into(viewAvatar);

        final List<Audio> audios = resource.audios;
        mAnimationDrawable = (AnimationDrawable) getResources().getDrawable(R.drawable.animation);
        if (audios != null && !audios.isEmpty()) {
            viewVoice.setImageResource(R.drawable.wifi);
            viewVoice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (player.isPlaying()) {
                        player.stop();
                        mAnimationDrawable.stop();
                        viewVoice.setImageResource(R.drawable.wifi);
                    } else {
                        player.setMCompletion(new AudioPlayer.MCompletion() {
                            @Override
                            public void Complete() {
                                mAnimationDrawable.stop();
                                viewVoice.setImageResource(R.drawable.wifi);
                            }
                        });
                        viewVoice.setImageDrawable(mAnimationDrawable);
                        player.play(RtTrendDetailActivity.this, audios.get(0).mUrl);
                        mAnimationDrawable.start();
                    }
                }
            });
        } else {
            viewVoice.setVisibility(View.GONE);
            if (mAnimationDrawable != null) {
                mAnimationDrawable.stop();
            }
        }

        final ArrayList<String> picLinks = new ArrayList<String>();
        List<Picture> pics = resource.pics;
        for (Picture dpp : pics) {
            picLinks.add(dpp.mUrl);
        }

        List<Picture> thumbnails = resource.thumbnails;
        if (thumbnails != null && !thumbnails.isEmpty()){
            gallery.setVisibility(View.VISIBLE);
            final ArrayList<String> links = new ArrayList<String>();
            for (Picture thumbnail : thumbnails) {
                links.add(thumbnail.mUrl);
            }
            gallery.setAdapter(new TrendsGridAdapter(links, RtTrendDetailActivity.this));
            gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    imageBrowser(position, picLinks);
                }
            });
        } else {
            gallery.setVisibility(View.GONE);
        }

        performLoadNoteList(resource.id);
    }

    private void imageBrowser(int position, ArrayList<String> links) {
        Intent intent = new Intent(RtTrendDetailActivity.this, ImagePagerActivity.class);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, links);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
        RtTrendDetailActivity.this.startActivity(intent);
    }
}
